package cn.gov.cus.rmftquartz.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Component;

/**
 * @author wxming.
 * @date 2018/2/9.
 */
@Slf4j
@Component
public class JobUtil {

    /**
     * @param scheduler 调度器
     * @param jobDetail 定时任务任务
     * @param jobTrigger 触发器
     */
    public void scheduleClusterJob(Scheduler scheduler,JobDetail jobDetail,Trigger jobTrigger){
        JobKey jobKey = jobDetail.getKey();
        TriggerKey triggerKey = jobTrigger.getKey();

        try {
            if (scheduler.checkExists(jobKey)) {
                // 如果数据库中已经存在调度任务,则替换 Job 内容但是 Trigger 触发的频率以数据库的为准.
                jobTrigger = scheduler.getTrigger(triggerKey);
                scheduler.unscheduleJob(triggerKey);
                scheduler.scheduleJob(jobDetail, jobTrigger);
            } else {
                // 没有则新增调度任务
                scheduler.scheduleJob(jobDetail, jobTrigger);
            }

        } catch (SchedulerException e) {
            log.error("Execute Job({}.{}) Failed!Exception: {}", jobKey.getGroup(), jobKey.getName(),ExceptionHelper.getExMsg(e));
        }

    }
}
